package org.net5ijy.security.config.service;

import java.util.ArrayList;
import java.util.List;

import org.net5ijy.security.bean.Role;
import org.net5ijy.security.bean.User;
import org.net5ijy.security.bean.util.UserState;
import org.net5ijy.security.config.security.SecurityConfig;
import org.net5ijy.security.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * CustomUserDetailsService
 *
 * @author XGF
 * @date 2020/11/30 22:35
 */
@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

  private static Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);

  @Autowired
  private UserService userService;

  @Override
  public UserDetails loadUserByUsername(String username)
      throws UsernameNotFoundException {
    User user = userService.getUser(username);
    if (user == null) {
      log.error("Username not found: " + username);
      throw new UsernameNotFoundException("Username not found: "
          + username);
    }
    return new org.springframework.security.core.userdetails.User(
        user.getUsername(), user.getPassword(), user.getState().equals(
        UserState.ACTIVE.getState()), true, true, true,
        getGrantedAuthorities(user));
  }

  static List<GrantedAuthority> getGrantedAuthorities(User user) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    for (Role r : user.getRoles()) {
      authorities.add(new SimpleGrantedAuthority(
          SecurityConfig.ROLE_PREFIX + r.getRoleName()));
    }
    log.info("用户{}拥有{}权限", user.getUsername(), authorities);
    return authorities;
  }
}
